import { defineStore } from "pinia";
import config from "@/config";
import { addUserLocation } from '@/utils/ty.js'
import { licationTime, orderTime } from '@/utils/config.js'
import { modal } from "@/plugins"
import { env, navigationName, navigationLogo } from '@/api/system/common'
import { orderMaxId } from '@/api/erp_api/order'
import { test } from 'uview-plus'
import { allProvince } from "@/api/erp_api/region"

const useSetStore = defineStore("set", {
  state: () => ({
    baseUrl: config.baseUrl,
		barHright: 50,
		timer: null,
		orderTimer: null,
		openTimer: true,
		menuClicks: [],
		appLogo: '',
		appName: '',
		salesmanClueParams: {},
		allProvinceList: [],
		purchaseOrder: {}
  }),
  actions: {
		// 采购单商品
		setPurchaseOrderList(res) {
			this.purchaseOrder = res
			uni.setStorageSync('purchaseOrder', res)
		},
		// 获取系统区域
		getAllProvinceList() {
			return new Promise((resolve, reject) => {
			  allProvince().then((res) => {
			  	// console.log(res)
			  	const list = res.data.map(item => {
						return {
							...item,
							value: item.code,
							text: item.name
						}
					}) || []
					this.allProvinceList = list
					resolve(list)
			  }).catch((err) => {
					reject(err)
				})
			})
		},
    // 设置服务器地址
    setBaseUrl(url) {
      this.baseUrl = url
      uni.setStorageSync('tyUrl', url)
    },
		// 设置页面bar高度
		setBarHeight(height) {
		  this.barHright = height
		},
		// 定位定时任务
		setTimer(userId) {
			if (!this.timer && userId && this.openTimer) {
				console.log('开始定位')
				this.addUserLocationFun(userId)
				this.timer = setInterval(() => {
					this.addUserLocationFun(userId)
				}, licationTime)
			}
		},
		addUserLocationFun(userId) {
			const locationTime = uni.getStorageSync('locationTime') || 0
			const nowTime = Date.now()
			if (nowTime - locationTime < (licationTime - 2000)) return false
			addUserLocation(userId).then(res => {
				if (res.code === 200) {
					// const nowTime = Date.now()
					uni.setStorageSync('locationTime', nowTime)
				}
			})
		},
		clearTimer() {
			console.log('清空定位')
			clearInterval(this.timer)
			this.timer = null
		},
		// 订单查询定时任务
		setOrderTimer(userId) {
			// 订单查询
			if (!this.orderTimer && userId && this.openTimer) {
				console.log('开始订单')
				this.getOrderMaxId()
				this.orderTimer = setInterval(() => {
					this.getOrderMaxId()
				}, orderTime)
			}
		},
		clearOrderTimer() {
			console.log('清空订单')
			clearInterval(this.orderTimer)
			this.orderTimer = null
		},
		getMenuClicks(userId, roleId) {
			let tyMenuClicks = uni.getStorageSync('tyMenuClicks') || []
			tyMenuClicks = tyMenuClicks.filter(item => item.u == userId && item.r == roleId)
			this.menuClicks = tyMenuClicks
			return this.menuClicks
		},
		setMenuClicks(userId, roleId, p1, p2) {
			let tyMenuClicks = uni.getStorageSync('tyMenuClicks') || []
			tyMenuClicks = tyMenuClicks.filter(item => item.u == userId && item.r == roleId)
			const clickName = `${userId}-${roleId}-${p1}-${p2}`
			const filterChick = tyMenuClicks.filter(item => {
				const name = `${item.u}-${item.r}-${item.p1}-${item.p2}`
				return name === clickName
			})
			if (filterChick.length > 0) {
				tyMenuClicks = tyMenuClicks.map(item => {
					const name = `${item.u}-${item.r}-${item.p1}-${item.p2}`
					if (name === clickName) {
						item.c += 1
					}
					return item
				})
			} else {
				tyMenuClicks.push({
					u: userId,
					r: roleId,
					p1: p1,
					p2: p2,
					c: 1
				})
			}
			this.menuClicks = tyMenuClicks
			uni.setStorageSync('tyMenuClicks', tyMenuClicks)
		},
		getEnv() {
			return new Promise((resolve, reject) => {
			  env().then((res) => {
			  	// console.log(res)
			  	this.env = res.msg
					resolve(res.msg)
			  	// if (res.msg === 'test') {
			  	// 	uni.setTabBarStyle({
			  	// 		backgroundColor: '#2c9af1'
			  	// 	})
			  	// }
			  }).catch((err) => {
					reject(err)
				})
			})
		},
		// 获取最大订单数
		getOrderMaxId() {
			return new Promise((resolve, reject) => {
			  orderMaxId().then((res) => {
			  	// console.log(res)
					const mId = uni.getStorageSync('mId') || ''
					if (mId && test.digits(res.data) && test.digits(mId) && parseInt(res.data) > parseInt(mId)) {
						uni.showToast({
							title: `您有新的订单，请及时查看。`,
							duration: 3000,
							icon: 'none'
						})
						const audioCtx = uni.createInnerAudioContext()
						audioCtx.src = '/static/images/order.mp3'
						audioCtx.play()
					}
					uni.setStorageSync('mId', res.data)
					resolve(res.msg)
			  }).catch((err) => {
					reject(err)
				})
			})
		},
		// 获取appLogo
		setAppLogo() {
			return new Promise((resolve, reject) => {
			  navigationLogo().then((res) => {
					this.appLogo = res.data
					resolve(res.data)
			  }).catch((err) => {
					reject(err)
				})
			})
		},
		// 获取app名称
		setAppName() {
			return new Promise((resolve, reject) => {
			  navigationName().then((res) => {
					this.appName = res.data
					resolve(res.data)
			  }).catch((err) => {
					reject(err)
				})
			})
		},
		setSalesmanClueParams(params) {
			// console.log(params)
			this.salesmanClueParams = params
		}
  },
});

export default useSetStore;
